const createError = require('http-errors');
const express = require('express');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const wxRouter = require('./routes/wx');
const punchPlansRouter = require('./routes/punch-plans');
const { authenticateToken } = require('./middleware/auth');

const app = express();

// 移除视图引擎配置

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// 移除静态文件服务，因为只提供API接口

app.use('/', indexRouter);
// 先挂载登录接口，不需要token验证
app.post('/api/users/login', usersRouter);
// 其他用户接口需要token验证
app.use('/api/users', authenticateToken, usersRouter);
app.use('/api/wx', wxRouter);
app.use('/api/punch-plans', punchPlansRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// 错误处理 - 返回JSON格式
app.use(function(err, req, res, next) {
  // 设置状态码
  res.status(err.status || 500);
  
  // 返回JSON错误信息
  res.json({
    message: err.message,
    error: req.app.get('env') === 'development' ? err : {}
  });
});

module.exports = app;
